package com.yuyou.fn.activity.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wens.mybatisplus.annotations.TableField;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.yuyou.fn.activity.constant.ActivityResourceWayEnum;
import com.yuyou.fn.activity.entity.*;
import com.yuyou.fn.activity.service.*;
import com.yuyou.fn.activity.vo.*;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.crm.entity.CrmDepartment;
import com.yuyou.fn.crm.entity.FromCategory;
import com.yuyou.fn.crm.service.ICrmDepartmentService;
import com.yuyou.fn.crm.service.ICustomerResourceService;
import com.yuyou.fn.crm.service.IFromCategoryService;
import com.yuyou.fn.crm.service.IMarketImportService;
import com.yuyou.fn.crm.vo.ImportCustomerResourceVo;
import com.yuyou.fn.educational.entity.BaseGrade;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.entity.Student;
import com.yuyou.fn.educational.service.IBaseGradeService;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.educational.service.IStudentRegService;
import com.yuyou.fn.educational.service.IStudentService;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.report.entity.MergeStudentRegDetail;
import com.yuyou.fn.report.service.IMergeStudentRegDetailService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;

import com.yuyou.fn.activity.mapper.ActivityRegSituationMapper;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 *
 * ActivityRegSituation 表数据服务层接口实现类
 *
 */
@Service
public class ActivityRegSituationServiceImpl extends SuperServiceImpl<ActivityRegSituationMapper, ActivityRegSituation,Long> implements IActivityRegSituationService {

    @Resource
    private IStudentService studentService;

    @Resource
    private IActivityService activityService;

    @Resource
    private IStudentRegService studentRegService;

    @Resource
    private IMergeStudentRegDetailService mergeStudentRegDetailService;

    @Resource
    private ICampusService campusService;

    @Resource
    private IBaseGradeService baseGradeService;

    @Resource
    private IActivityTargetService activityTargetService;

    @Resource
    private IActivityCampusSessionService activityCampusSessionService;

    @Resource
    private IActivityCampusService activityCampusService;

    @Resource
    private IMarketImportService marketImportService;

    @Resource
    private IFromCategoryService fromCategoryService;

    @Resource
    private ICrmDepartmentService crmDepartmentService;

    @Resource
    private ICustomerResourceService customerResourceService;

    @Override
    @Transactional
    public ActivityRegSituation saveActivityRegSituation(ActivityRegSaveVo activityRegSaveVo) {
        ActivityRegSituation have = this.findActivityRegSituationByNamePhoneSession(activityRegSaveVo.getActivityId(), activityRegSaveVo.getStudentName(), activityRegSaveVo.getStudentPhoneNo(), activityRegSaveVo.getActivityCampusSessionId());
        ActivityRegSituation activityRegSituation=new ActivityRegSituation();

        activityRegSituation.setUpdateTime(TimeUtils.now());
        Boolean insertState=false;
        if (have==null){
            insertState=true;
            activityRegSituation.setCreateTime(TimeUtils.now());
            activityRegSituation.setActivityRegSituationId(IdWorker.getId());
            activityRegSituation.setSignStatus(0);
        }else {
            activityRegSituation.setActivityRegSituationId(have.getActivityRegSituationId());
            activityRegSituation.setSignStatus(have.getSignStatus());
        }

        Integer readStatus=0;
        Date firstReadTime=null;
        Activity activity=activityService.findById(activityRegSaveVo.getActivityId());
        ActivityCampusSession activityCampusSession=activityCampusSessionService.findById(activityRegSaveVo.getActivityCampusSessionId());

        if(activity.getShelvesStatus().equals(0)){
            throw new BusException("活动已结束！");
        }

        Long l = this.countByActivityCampusSessionId(activityRegSaveVo.getActivityCampusSessionId());

        if (activity.getMaxRegNum().intValue()<=l.intValue()){
            throw new BusException("报名人数已满，截止报名，谢谢！");
        }
        if (activity.getPeriodId()!=null){
            Student student=studentService.findByNameAndPhone(activityRegSaveVo.getStudentName(),activityRegSaveVo.getStudentPhoneNo());
            if (student!=null){
                List<MergeStudentRegDetail> mergeStudentRegDetailList=mergeStudentRegDetailService.findByStudentIdPeriodIdsChargingStatuses(student.getStudentId(),Arrays.asList(activity.getPeriodId()),Arrays.asList(1,2));
                if (!Utils.isEmpty(mergeStudentRegDetailList)){
                    readStatus=1;
                    firstReadTime = mergeStudentRegDetailList.get(0).getCreateTime();
                }
            }

        }


        activityRegSituation.setActivityId(activityRegSaveVo.getActivityId());
        activityRegSituation.setCampusId(activityRegSaveVo.getCampusId());
        activityRegSituation.setStudentName(activityRegSaveVo.getStudentName());
        activityRegSituation.setStudentPhoneNo(activityRegSaveVo.getStudentPhoneNo());
        activityRegSituation.setGradeId(activityRegSaveVo.getGradeId());
        activityRegSituation.setOtherMsg(JSONObject.toJSONString(activityRegSaveVo.getOtherMsg()));

        activityRegSituation.setReadStatus(readStatus);
        activityRegSituation.setFirstReadTime(firstReadTime);
        activityRegSituation.setActivityCampusId(activityCampusSession.getActivityCampusId());
        activityRegSituation.setActivityCampusSessionId(activityCampusSession.getActivityCampusSessionId());
        activityRegSituation.setSessionNo(activityCampusSession.getSessionNo());
        if (insertState){
            this.insertSelective(activityRegSituation);
        }else {
            this.updateSelectiveById(activityRegSituation);
        }

        /*未报读导入潜客*/
        if(readStatus==0 && insertState){
            Threads.dispatch(new Runnable() {
                @Override
                public void run() {
                    importToCrmResourceWithOutRead(activity,Arrays.asList(activityRegSituation));
                }
            });
        }

        return activityRegSituation;
    }


    @Override
    public void importActivityRegSituation(long acitivityId, List<ImportActivityRegVo> importActivityRegVoList) {
        if (Utils.isEmpty(importActivityRegVoList)){
            return;
        }

        Activity activity=activityService.findById(acitivityId);
        if(activity.getShelvesStatus().equals(0)){
            throw new BusException("活动已结束！");
        }

        List<ActivityCampusDetailVo> activityCampusDetailVoList=activityCampusService.findActivityCampusListByActivityId(acitivityId);
        Map<String, ActivityCampusDetailVo> activivtyCampusMap = BeanUtils.toMap(activityCampusDetailVoList, "campusName");

        List<String> studentNames=BeanUtils.toList(importActivityRegVoList,"studentName");
        List<String> studentPhones=BeanUtils.toList(importActivityRegVoList,"studentPhones");
        List<Student> studentList=studentService.findByStudentNamesAndPhonesOrSlavePhones(studentNames,studentPhones,studentPhones);
        Map<String, List<Student>> studentNameMap = BeanUtils.toGroup(studentList, "name");

        List<BaseGrade> baseGradeList=baseGradeService.findAllOrderGrade();
        Map<String,BaseGrade> baseGradeMap=BeanUtils.toMap(baseGradeList,"gradeName");

        Map<String,Long> namePhoneIdMap=new HashMap<>();//记录该学生（姓名+手机号）是否存在系统里面,key:name_phone,value studentId

        Map<String,ActivityCampusSession> activivtyCampusSessionMap=new HashMap<>();//key:campusId_sessionNo,value:ActivityCampusSession
        Map<String,Integer> activivtyCampusSessionRegNumMap=new HashMap<>();//key:campusId_sessionNo,value:条数
        List<Long> activityCampusSessionIds=new ArrayList<>();
        List<Long> studentIds=new ArrayList<>(studentList.size());//记录已经存在系统的学生；
        for (ImportActivityRegVo importActivityRegVo:importActivityRegVoList){
            String key=importActivityRegVo.getStudentName()+"_"+importActivityRegVo.getStudentPhoneNo();
            List<Student> oneNameStudentList=studentNameMap.get(importActivityRegVo.getStudentName());
            if (oneNameStudentList!=null){
                for (Student student:oneNameStudentList){
                    if (importActivityRegVo.getStudentPhoneNo().equals(student.getPhoneNo()) || importActivityRegVo.getStudentPhoneNo().equals(student.getSlavePhoneNo())){
                        namePhoneIdMap.put(key,student.getStudentId());
                        studentIds.add(student.getStudentId());
                        break;
                    }
                }
            }
            ActivityCampusDetailVo activityCampusDetailVo=activivtyCampusMap.get(importActivityRegVo.getCampusName());
            List<ActivityCampusSession> activityCampusSessionList=activityCampusDetailVo.getActivityCampusSessionList();
            for (ActivityCampusSession activityCampusSession:activityCampusSessionList){
                if (activityCampusSession.getSessionNo().equals(importActivityRegVo.getSessionNo())){
                    String activivtyCampusSessionkey=importActivityRegVo.getCampusName()+"_"+importActivityRegVo.getSessionNo();
                    activivtyCampusSessionMap.put(activivtyCampusSessionkey,activityCampusSession);
                    activityCampusSessionIds.add(activityCampusSession.getActivityCampusSessionId());
                    activivtyCampusSessionRegNumMap.put(key,activivtyCampusSessionRegNumMap.get(activivtyCampusSessionkey)==null?0:activivtyCampusSessionRegNumMap.get(activivtyCampusSessionkey)+1);
                    break;
                }
            }
        }


        List<ActivityRegSituation> checkRegList=this.findByActivityCampusSessionIds(activityCampusSessionIds,"activityRegSituationId");
        Map<String,ActivityRegSituation> uqRegMap=new HashMap<>();
        for (ActivityRegSituation activityRegSituation:checkRegList){
            String uqRegKey=activityRegSituation.getActivityCampusSessionId()+"_"+activityRegSituation.getStudentName()+"_"+activityRegSituation.getStudentPhoneNo();
            uqRegMap.put(uqRegKey,activityRegSituation);
        }


        Map<Long, List<ActivityRegSituation>> checkRegMap = BeanUtils.toGroup(checkRegList, "activityCampusSessionId");

        List<MergeStudentRegDetail> mergeStudentRegDetailList = mergeStudentRegDetailService.findByStudentIdsPeriodIdsChargingStatuses(studentIds, Arrays.asList(activity.getPeriodId()), Arrays.asList(1, 2));
        Map<Long, List<MergeStudentRegDetail>> regMap = BeanUtils.toGroup(mergeStudentRegDetailList, "studentId");

        List<ActivityRegSituation> activityRegSituationList=new ArrayList<>(importActivityRegVoList.size());
        List<ActivityRegSituation> crmImportList=new ArrayList<>(importActivityRegVoList.size());
        for (ImportActivityRegVo importActivityRegVo:importActivityRegVoList){
            Integer readStatus=0;
            String namePhoneKey=importActivityRegVo.getStudentName()+"_"+importActivityRegVo.getStudentPhoneNo();
            String campusSessionKey=importActivityRegVo.getCampusName()+"_"+importActivityRegVo.getSessionNo();
            Long studentId=namePhoneIdMap.get(namePhoneKey);
            if (studentId!=null && regMap.containsKey(studentId)){
                readStatus=1;
            }
            ActivityCampusDetailVo activityCampusDetailVo=activivtyCampusMap.get(importActivityRegVo.getCampusName());
            ActivityCampusSession activityCampusSession=activivtyCampusSessionMap.get(campusSessionKey);
            if (activityCampusSession==null){
                throw new BusException("校区"+importActivityRegVo.getCampusName()+",场次为"+importActivityRegVo.getSessionNo()+"的活动不存在");
            }

            Integer havingRegNum=checkRegMap.get(campusSessionKey)==null?0:checkRegMap.get(campusSessionKey).size();
            Integer importRegNum=activivtyCampusSessionRegNumMap.get(campusSessionKey)==null?0:activivtyCampusSessionRegNumMap.get(campusSessionKey);
            if (importRegNum+havingRegNum>activity.getMaxRegNum()){
                throw new BusException("校区："+activityCampusDetailVo.getCampusName()+"第"+activityCampusSession.getSessionNo()+"场超过活动最大报名人数");
            }


            ActivityRegSituation activityRegSituation=new ActivityRegSituation();
            activityRegSituation.setActivityRegSituationId(IdWorker.getId());
            activityRegSituation.setActivityId(activity.getActivityId());
            activityRegSituation.setCampusId(activityCampusDetailVo.getCampusId());
            activityRegSituation.setStudentName(importActivityRegVo.getStudentName());
            activityRegSituation.setStudentPhoneNo(importActivityRegVo.getStudentPhoneNo());
            activityRegSituation.setGradeId(baseGradeMap.get(importActivityRegVo.getGradeName()).getGradeId());
            activityRegSituation.setOtherMsg(new JSONObject().toJSONString());
            activityRegSituation.setSignStatus(0);
            activityRegSituation.setReadStatus(readStatus);
            activityRegSituation.setActivityCampusId(activityCampusSession.getActivityCampusId());
            activityRegSituation.setActivityCampusSessionId(activityCampusSession.getActivityCampusSessionId());
            activityRegSituation.setSessionNo(activityCampusSession.getSessionNo());
            activityRegSituation.setCreateTime(TimeUtils.now());
            activityRegSituation.setUpdateTime(TimeUtils.now());
            String uqRegKey=activityRegSituation.getActivityCampusSessionId()+"_"+activityRegSituation.getStudentName()+"_"+activityRegSituation.getStudentPhoneNo();
            if (uqRegMap.containsKey(uqRegKey)){
                throw new BusException("有重复数据");
            }
            activityRegSituationList.add(activityRegSituation);



            if (activityRegSituation.getReadStatus()==0){
                crmImportList.add(activityRegSituation);
            }
        }
        if (activityRegSituationList.size()>0){
            this.insertBatch(activityRegSituationList);
        }
        if (crmImportList.size()>0){
            Threads.dispatch(new Runnable() {
                @Override
                public void run() {
                    importToCrmResourceWithOutRead(activity,crmImportList);
                }
            });
        }

    }

    private void importToCrmResourceWithOutRead(Activity activity, List<ActivityRegSituation> activityRegSituationList){
        List<Long> categoryIds=new ArrayList<>(2);
        categoryIds.add(activity.getParentFromCategoryId());
        categoryIds.add(activity.getChildFromCategoryId());
        List<FromCategory> fromCategories=fromCategoryService.findByIds(categoryIds);
        Map<Long, FromCategory> fromCategoryMap = BeanUtils.toMap(fromCategories, "categoryId");
        List<Long> campusIds = BeanUtils.toList(activityRegSituationList, "campusId");
        List<Campus> campusList=campusService.findByIds(campusIds);
        Map<Long, Campus> campusMap = BeanUtils.toMap(campusList, "campusId");

        Map<Long,BaseGrade> baseGradeMap=baseGradeService.findGradeMap();


        CrmDepartment crmDepartment=crmDepartmentService.findByAreaTeamIdAndName(activity.getAreaTeamId(),"市场部");
        if (crmDepartment==null){
            throw new BusException("请添加市场部");
        }
        Principals.Principal principal=Principals.get();
        if (principal==null){
            principal = new Principals.Principal(0L, activity.getActivityName()+"导入");
        }
        List<ImportCustomerResourceVo> importCustomerResourceVoList=new ArrayList<>(activityRegSituationList.size());
        for (ActivityRegSituation activityRegSituation:activityRegSituationList){
            ImportCustomerResourceVo importCustomerResourceVo=new ImportCustomerResourceVo();
            importCustomerResourceVo.setPriority("中");
            BaseGrade baseGrade=baseGradeMap.get(activityRegSituation.getGradeId());
            Campus campus=campusMap.get(activityRegSituation.getCampusId());
            importCustomerResourceVo.setGradeName(baseGrade.getGradeName());
            importCustomerResourceVo.setCampusName(campus.getCampusName());
            FromCategory childFromCategory = fromCategoryMap.get(activity.getChildFromCategoryId());
            importCustomerResourceVo.setFromSmallCategoryName(childFromCategory==null?"":childFromCategory.getCategoryName());
            FromCategory parentFromCategory = fromCategoryMap.get(activity.getParentFromCategoryId());
            importCustomerResourceVo.setFromBigCategoryName(parentFromCategory==null?"":parentFromCategory.getCategoryName());

            importCustomerResourceVo.setProjectTime(Utils.formatDate(activity.getActivityStartDate(),"yyyy-MM-dd"));
            importCustomerResourceVo.setProjectName(activity.getActivityName());
            importCustomerResourceVo.setPhoneNo(activityRegSituation.getStudentPhoneNo());
            importCustomerResourceVo.setStudentName(activityRegSituation.getStudentName());
            importCustomerResourceVo.setActivityRegSituationId(activityRegSituation.getActivityRegSituationId());
            importCustomerResourceVo.setSignStatus(0);
            importCustomerResourceVoList.add(importCustomerResourceVo);
        }


        marketImportService.importCustomerResource(activity.getAreaTeamId(),crmDepartment.getDepartmentId(),importCustomerResourceVoList,principal);

    }

    @Override
    public List<ActivityRegSituation> findActivityRegSituationListByNamePhone(Long activityId, String studentName, String studentPhoneNo) {
        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("studentName",studentName);
        criteria.andEqualTo("studentPhoneNo",studentPhoneNo);
        example.orderBy("createTime").desc();
        return this.findListByExample(example);
    }

    @Override
    public ActivityRegSituation findActivityRegSituationByNamePhoneSession(Long activityId, String studentName, String studentPhoneNo, Long activityCampusSessionId) {
        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("studentName",studentName);
        criteria.andEqualTo("studentPhoneNo",studentPhoneNo);
        criteria.andEqualTo("activityCampusSessionId",activityCampusSessionId);
        return this.findOneByExample(example);
    }

    @Override
    public ActivityRegListVo findActivityRegSessionListByNamePhone(Long activityId, String studentName, String studentPhoneNo) {
        ActivityRegListVo activityRegListVo=new ActivityRegListVo();
        Activity activity=activityService.findById(activityId,"activityId","activityName");
        activityRegListVo.setActivityId(activityId);
        activityRegListVo.setActivityName(activity.getActivityName());
        List<ActivityRegSituation> activityRegSituationList = this.findActivityRegSituationListByNamePhone(activityId, studentName, studentPhoneNo);
        if (Utils.isEmpty(activityRegSituationList)){
            activityRegListVo.setActivityRegSessionDetailVoList(Collections.EMPTY_LIST);
            return activityRegListVo;
        }

        List<Long> campusIds = Utils.removeDuplicate(BeanUtils.toList(activityRegSituationList, "campusId"));
        List<Campus> campusList=campusService.findByIds(campusIds);
        Map<Long, Campus> campusMap = BeanUtils.toMap(campusList, "campusId");

        List<Long> activitCampusSessionIds=BeanUtils.toList(activityRegSituationList,"activityCampusSessionId");
        List<ActivityCampusSession> activityCampusSessionList = activityCampusSessionService.findByIds(activitCampusSessionIds);
        Map<Long, ActivityCampusSession> campusSessionMap = BeanUtils.toMap(activityCampusSessionList, "activityCampusSessionId");

        List<ActivityRegSessionDetailVo> activityRegSessionDetailVoList = Lists.transform(activityRegSituationList, item -> {
            ActivityCampusSession activityCampusSession = campusSessionMap.get(item.getActivityCampusSessionId());
            ActivityRegSessionDetailVo activityRegSessionDetailVo = new ActivityRegSessionDetailVo();
            activityRegSessionDetailVo.setActivityRegSituationId(item.getActivityRegSituationId());
            activityRegSessionDetailVo.setActivityCampusSessionId(item.getActivityCampusSessionId());
            activityRegSessionDetailVo.setCampusId(item.getCampusId());
            activityRegSessionDetailVo.setCampusName(campusMap.get(item.getCampusId()).getCampusName());
            activityRegSessionDetailVo.setSessionMsg(activityCampusSession.getSessionMsg());
            activityRegSessionDetailVo.setSessionNo(activityCampusSession.getSessionNo());
            activityRegSessionDetailVo.setSignStatus(item.getSignStatus());
            return activityRegSessionDetailVo;
        });
        activityRegListVo.setActivityRegSessionDetailVoList(activityRegSessionDetailVoList);

        return activityRegListVo;
    }

    @Override
    @Transactional
    public void signActivityRegSituation(ActivitySignVo activitySignVo) {
        ActivityRegSituation activityRegSituation=this.findById(activitySignVo.getActivityRegSituationId());

        if (activityRegSituation.getSignStatus()==1){
            throw new BusException("已签到");
        }

        ActivityTarget activityTarget = activityTargetService.findActivityTargetByActivityIdCampusId(activityRegSituation.getActivityId(), activityRegSituation.getCampusId());

        if (!activityTarget.getSignStatus().equals(1)){
            throw new BusException("未到签到时间，请耐心等待！");
        }

        ActivityRegSituation update=new ActivityRegSituation();
        BeanUtils.copyProperties(update,activitySignVo);
        update.setSignTime(TimeUtils.now());
        update.setUpdateTime(TimeUtils.now());
        update.setSignStatus(1);
        this.updateSelectiveById(update);
        customerResourceService.updateSignStatusByActivityRegSituationId(activityRegSituation.getActivityRegSituationId(),1);
    }

    @Override
    public Page<ActivityRegSituationDetailVo> findActivityRegSituationPage(DataPermission dataPermission,ActivityRegSituationQueryVo activityRegSituationQueryVo, int pageNo, int pageSize) {
        Activity activity=activityService.findById(activityRegSituationQueryVo.getActivityId());
        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria,activityRegSituationQueryVo);
        criteria.andIn("campusId",dataPermission.getCampusIds());
        Page<ActivityRegSituation> activityRegSituationPage = this.findPageByExample(example, pageNo, pageSize);
        List<ActivityRegSituation> activityRegSituations=activityRegSituationPage.getRecords();

        Page<ActivityRegSituationDetailVo> activityRegSituationDetailVoPage=Utils.newPage(activityRegSituationPage);
        if (Utils.checkListNotEmpty(activityRegSituations)){
            List<ActivityRegSituationDetailVo> activityRegSituationDetailVoList=new ArrayList<>(activityRegSituations.size());
            List<Long> campusIds = Utils.removeDuplicate(BeanUtils.toList(activityRegSituations, "campusId"));


            List<Campus> campusList=campusService.findByIds(campusIds);
            Map<Long, Campus> campusMap = BeanUtils.toMap(campusList, "campusId");
            Map<Long, BaseGrade> gradeMap = baseGradeService.findGradeMap();

            for(ActivityRegSituation activityRegSituation:activityRegSituations){
                ActivityRegSituationDetailVo activityRegSituationDetailVo=new ActivityRegSituationDetailVo();
                BeanUtils.copyProperties(activityRegSituationDetailVo,activityRegSituation);
                activityRegSituationDetailVo.setActivityStartDate(activity.getActivityStartDate());
                activityRegSituationDetailVo.setActivityName(activity.getActivityName());
                activityRegSituationDetailVo.setGradeName(gradeMap.get(activityRegSituation.getGradeId()).getGradeName());

                activityRegSituationDetailVo.setCampusName(campusMap.get(activityRegSituation.getCampusId()).getCampusName());

                activityRegSituationDetailVoList.add(activityRegSituationDetailVo);
            }
            activityRegSituationDetailVoPage.setRecords(activityRegSituationDetailVoList);
        }
        return activityRegSituationDetailVoPage;
    }

    @Override
    public SXSSFWorkbook exportActivityRegSituationDetail(DataPermission dataPermission,ActivityRegSituationQueryVo activityRegSituationQueryVo) {
        Page<ActivityRegSituationDetailVo> activityRegSituationPage = this.findActivityRegSituationPage(dataPermission,activityRegSituationQueryVo, 1, 10000);
        Activity activity=activityService.findById(activityRegSituationQueryVo.getActivityId());
        return activityRegSituation2excel(activityRegSituationPage.getRecords(),activity);
    }

    public static SXSSFWorkbook activityRegSituation2excel(List<ActivityRegSituationDetailVo> activityRegSituationDetailVoList,Activity activity) {
        List<InputVo> inputVoList=JSONObject.parseArray(activity.getShowFields(),InputVo.class);
        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("活动报名签到数据");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{ "活动名称","活动时间","意向校区","场次","学生姓名","电话号码","年级","是否已签到","签到时间","是否转化","是否在读（活动期数）","消息来源","是否需要一对一诊断"};

        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        if (!Utils.isEmpty(inputVoList)){
            for (int i=0;i<inputVoList.size();i++){
                firstRow.createCell(titles.length+i).setCellValue(inputVoList.get(i).getTitle());
            }
        }



        int rowNum = 1;

        if (activityRegSituationDetailVoList!=null){
            for (ActivityRegSituationDetailVo activityRegSituationDetailVo : activityRegSituationDetailVoList) {
                int cellNum = 0;
                activityRegSituationDetailVo.getOtherMsg();
                JSONObject jsonObject=JSONObject.parseObject(activityRegSituationDetailVo.getOtherMsg());
                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityRegSituationDetailVo.getActivityName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(activityRegSituationDetailVo.getActivityStartDate()==null?"":Utils.formatDate(activityRegSituationDetailVo.getActivityStartDate(),"yyyy-MM-dd"));


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityRegSituationDetailVo.getCampusName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityRegSituationDetailVo.getSessionNo().toString()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityRegSituationDetailVo.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityRegSituationDetailVo.getStudentPhoneNo()));


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(activityRegSituationDetailVo.getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(activityRegSituationDetailVo.getSignStatus()==0?"未签到":"已签到");

                cell = row.createCell(cellNum++);
                cell.setCellValue(activityRegSituationDetailVo.getSignTime()==null?"":Utils.formatDate(activityRegSituationDetailVo.getSignTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                Integer inTimeRead=0;
                Date firstReadTime=activityRegSituationDetailVo.getFirstReadTime();
                if (firstReadTime!=null && activityRegSituationDetailVo.getSignTime()!=null){
                    if (firstReadTime.after(TimeUtils.changeDateByNum(activityRegSituationDetailVo.getSignTime(),-7)) && firstReadTime.before(TimeUtils.changeDateByNum(activityRegSituationDetailVo.getSignTime(),7))){
                        inTimeRead=1;
                    }
                }
                cell.setCellValue(inTimeRead==0?"未转化":"已转化");


                cell = row.createCell(cellNum++);
                cell.setCellValue(activityRegSituationDetailVo.getReadStatus()==0?"未报读":"已报读");


                cell = row.createCell(cellNum++);
                cell.setCellValue(EnumUtils.getName(ActivityResourceWayEnum.values(),activityRegSituationDetailVo.getSourceWay()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(activityRegSituationDetailVo.getDiagnosisStatus()==null?"":activityRegSituationDetailVo.getDiagnosisStatus()==0?"不需要":"需要");

                if (!Utils.isEmpty(inputVoList)){
                    for (InputVo inputVo:inputVoList){
                        cell = row.createCell(cellNum++);
                        cell.setCellValue(StringUtils.defaultString(jsonObject.getString(inputVo.getTitle())));
                    }
                }

            }
        }
        return excel;
    }


    @Override
    public List<ActivityRegSituation> findByActivityIdsStudentNamePhoneNosReadStatus(List<Long> activityIds, String studentName, List<String> studentPhoneNos,Integer readStatus) {
        if (Utils.isEmpty(activityIds) || StringUtils.isEmpty(studentName) || Utils.isEmpty(studentPhoneNos)){
            return Collections.EMPTY_LIST;
        }
        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("activityId",activityIds);
        criteria.andEqualTo("studentName",studentName);
        criteria.andIn("studentPhoneNo",studentPhoneNos);
        criteria.andEqualTo("readStatus",readStatus);
        return this.findListByExample(example);
    }

    @Override
    public void updateReadStatusFirstReadTimeByIds(List<Long> activityRegSituationIds,Integer readStatus,Date firstReadTime) {
        if (Utils.isEmpty(activityRegSituationIds)){
            return;
        }
        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("activityRegSituationId",activityRegSituationIds);
        ActivityRegSituation activityRegSituation=new ActivityRegSituation();
        activityRegSituation.setReadStatus(1);
        activityRegSituation.setFirstReadTime(firstReadTime);
        this.updateSelectiveByExample(activityRegSituation,example);
    }

    @Override
    public Long countByActivityCampusSessionId(long activityCampusSessionId) {
        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("activityCampusSessionId",activityCampusSessionId);
        return this.countByExample(example);
    }

    @Override
    public List<ActivityRegSituation> findByActivityCampusSessionIds(List<Long> activityCampusSessionIds,String ...columns) {
        if (Utils.isEmpty(activityCampusSessionIds)){
            return Collections.EMPTY_LIST;
        }
        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("activityCampusSessionId",activityCampusSessionIds);
        return this.findListByExample(example);
    }

    @Override
    public List<ActivityRegSituation> findActivityRegSituationByActivityIdCampusIds(long activityId, List<Long> campusIds) {

        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("activityId",activityId);
        criteria.andIn("campusId",campusIds);
        return this.findListByExample(example);
    }

    @Override
    public List<ActivityQuantityVo> findActivityQuantityByActivityIds(List<Long> activityIds) {
        if (Utils.isEmpty(activityIds)){
            return Collections.EMPTY_LIST;
        }
        return autoMapper.findActivityQuantityByActivityIds(activityIds);
    }

    @Override
    public ActivitySessionNumVo findActivitySessionNum(long activityCampusSessionId) {
        return autoMapper.findActivitySessionNum(activityCampusSessionId);
    }

    @Override
    public List<ActivityRegSituation> findDiagnosisStudent(long activityCampusSessionId) {
        Example<ActivityRegSituation> example=ActivityRegSituation.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("diagnosisStatus",1);
        criteria.andEqualTo("activityCampusSessionId",activityCampusSessionId);
        return this.findListByExample(example);
    }

    @Override
    public ActivityNumVo findActivityNum(long activityCampusId) {
        return autoMapper.findActivityNum(activityCampusId);
    }
}